package com.example.mvvmdemo.data.network;

import com.example.mvvmdemo.data.Api;
import com.example.mvvmdemo.domain.ApiErrorExcepton;
import com.example.mvvmdemo.domain.model.ResponseBaseModel;
import com.example.mvvmdemo.domain.model.TestModel;
import com.example.mvvmdemo.domain.repository.ApiDataRepository;
import com.example.mvvmdemo.ui.Mapper;
import com.example.mvvmdemo.ui.model.TestModelVm;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

public class HttpDataRepository extends CommonRetrofit<Api> implements ApiDataRepository {

    @Inject
    public HttpDataRepository() {
    }

    @Override
    public Observable<List<TestModelVm>> testApi() {
        return getNetworkService().testApi().map(testdomainList -> {
            List<TestModelVm> data = new ArrayList<>();
            for (TestModel model : testdomainList.getData()) {
                data.add(Mapper.modelMappper(model));
            }
            return data;
        });
    }

    @Override
    public Observable<List> testErrorApi() {

        Observable<ResponseBaseModel<Object>> modelObservable = getNetworkService()
            .testErrorApi();
        return modelObservable
            .flatMap((Function<ResponseBaseModel<Object>, ObservableSource<List>>) model -> {
                if (model.getCode() != 0) {   //code不为0   请求未能正常执行
                    return Observable.error(new ApiErrorExcepton(model.getCode(), model.getMsg()));
                } else {   //数据正确的处理
                    return Observable.just(new ArrayList());
                }
            });
    }

    @Override
    protected Class<Api> getRestClass() {
        return Api.class;
    }
}
